﻿using Microsoft.Practices.Unity;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using Wicresoft.UnifyShow.Business;
using Wicresoft.UnifyShow.Business.Extensions;
using Wicresoft.UnifyShow.Business.Models;
using Wicresoft.UnifyShow.Business.Models.Plan.InsResult;
using Wicresoft.UnifyShow.BusinessImpl.Helpers;
using Wicresoft.UnifyShow.Utility;
using Wicresoft.UnifyShow2.Portal.Extensions;

namespace Wicresoft.UnifyShow2.Portal.Controllers
{
    [Authorize]
    public class PlanManagementController : BaseController
    {
        private IPlanManagement _plan;
        private IUser_X user_x;
        private ISiteBranch siteBranch;

        private readonly string GlobalCompanyName = "福建省烟草专卖局";

        protected override void Dispose(bool disposing)
        {
            ((IDisposable)user_x).Dispose();
            ((IDisposable)_plan).Dispose();
            ((IDisposable)siteBranch).Dispose();
        }

        [InjectionConstructor]
        public PlanManagementController(IPlanManagement planService, IUser_X _user_x, ISiteBranch _siteBranch)
        {
            _plan = planService;
            user_x = _user_x;
            siteBranch = _siteBranch;
        }

        public PlanManagementController() { }

        //
        // GET: /PlanManagement/

        public CultureInfo Culture
        {
            get
            {
                return new System.Globalization.CultureInfo("zh-CN");
            }
        }

        public ActionResult Index()
        {
            Thread.CurrentThread.CurrentCulture = Culture;
            Thread.CurrentThread.CurrentUICulture = Culture;

            SetRoles(user_x);

            ViewBag.IsConfigAdmin = IsConfigAdmin;
            ViewBag.IsPlanManage = true;

            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);
            if (CurrentUser == null)
            {
                throw new Exception("USER_X is null.");
            }
            var sites = user_x.GetSiteBranchByID(CurrentUser.ID);
            var t = sites.FirstOrDefault(s => s.Name == CurrentUser.Company);
            if (t == null)
            {
                throw new Exception("UserSite is null.");
            }

            //省局用户
            ViewData["IsGlobalUser"] = t.Alias.Equals("省局");

            ViewBag.UserDept = CurrentUser.Department;
            ViewBag.UserCompany = CurrentUser.Company;
            return View();
        }

        /// <summary>
        /// 日常巡检
        /// </summary>
        /// <returns></returns>
        public ActionResult RoutineInspection(int? ID)
        {
            SetRoles(user_x);
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);
            ViewBag.CurrentUser = CurrentUser;

            Thread.CurrentThread.CurrentCulture = Culture;
            Thread.CurrentThread.CurrentUICulture = Culture;

            //服务器机型下拉源
            ViewData["ServerType"] = new EnumDataSource<EnumUtility.ServerType>();
            // 用途下拉源
            ViewData["Using"] = _plan.GetUsingList();
            //品牌
            ViewData["Vendor"] = _plan.GetVendorList();
            //版本
            ViewData["Version"] = _plan.GetVersionList();

            //数据库版本
            ViewData["DBVersion"] = _plan.GetDBVersionList();

            //中间件版本
            ViewData["MiddleVersion"] = _plan.GetMiddleVersionList();

            //计划周期类型
            ViewData["PlanType"] = new EnumDataSource<EnumUtility.PlanType>();

            if (ID.HasValue && ID != 0)
            {
                ViewBag.DetailID = ID;

                var job = _plan.GetScheduleJobDetail(ID.Value);

                if (job != null && job.Job != null)
                {
                    var owner = user_x.GetUserByID(job.Job.JobOwnerID);
                    if (owner != null)
                    {
                        job.Job.JobOwnerName = owner.DisplayName;
                    }

                    var tasker = user_x.GetUserByID(job.Job.TaskUserID);
                    if (tasker != null)
                    {
                        job.Job.TaskUserName = tasker.DisplayName;
                    }
                }

                ViewData["Model"] = job;
            }

            return View();
        }

        /// <summary>
        /// 第三方巡检
        /// </summary>
        /// <returns></returns>
        public ActionResult ThirdPartyInspection(int? ID)
        {
            Thread.CurrentThread.CurrentCulture = Culture;
            Thread.CurrentThread.CurrentUICulture = Culture;

            decimal totalCount = 0;
            //第三方巡检类型
            ViewData["ThirdInspectionType"] = _plan.GetAllInspectionType(out totalCount, null, null);

            SetRoles(user_x);
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);
            ViewBag.CurrentUser = CurrentUser;
            var sites = user_x.GetSiteBranchByID(CurrentUser.ID);
            var t = sites.FirstOrDefault(s => s.Name == CurrentUser.Company);
            if (t == null)
            {
                throw new Exception("UserSite is null.");
            }

            //巡检范围
            var range = new List<PlanLocationOwner>() { _plan.GetInterfacePeopleByLocationID(t.ID) };
            ViewData["IsGlobal"] = t.Alias.Equals("省局");
            if (t.Alias.Equals("省局"))
            {
                range = _plan.GetSiteALLBranch().OrderBy(x => x.LocationID).ToList();
            }
            ViewData["InspectionRange"] = range;
            //计划周期类型
            ViewData["PlanType"] = new EnumDataSource<EnumUtility.PlanType>();

            if (ID.HasValue && ID != 0)
            {
                ViewBag.DetailID = ID;
                var job = _plan.GetScheduleJobDetail(ID.Value);

                if (job != null && job.Job != null)
                {
                    var owner = user_x.GetUserByID(job.Job.JobOwnerID);
                    if (owner != null)
                    {
                        job.Job.JobOwnerName = owner.DisplayName;
                    }

                    var tasker = user_x.GetUserByID(job.Job.TaskUserID);
                    if (tasker != null)
                    {
                        job.Job.TaskUserName = tasker.DisplayName;
                    }
                }

                ViewData["Model"] = job;
            }

            return View();
        }

        /// <summary>
        /// 一般计划任务
        /// </summary>
        /// <returns></returns>
        public ActionResult GeneralPlan(int? ID)
        {
            Thread.CurrentThread.CurrentCulture = Culture;
            Thread.CurrentThread.CurrentUICulture = Culture;

            //计划范围
            ViewData["InspectionRange"] = _plan.GetSiteALLBranch().OrderBy(x => x.LocationID).ToList();
            //计划周期类型
            ViewData["PlanType"] = new EnumDataSource<EnumUtility.PlanType>();

            SetRoles(user_x);
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);
            ViewBag.CurrentUser = CurrentUser;

            if (ID.HasValue && ID != 0)
            {
                ViewBag.DetailID = ID;
                var job = _plan.GetScheduleJobDetail(ID.Value);
                TempData["JobDetail"] = job;
                if (job != null && job.Job != null)
                {
                    var owner = user_x.GetUserByID(job.Job.JobOwnerID);
                    if (owner != null)
                    {
                        job.Job.JobOwnerName = owner.DisplayName;
                    }

                    var tasker = user_x.GetUserByID(job.Job.TaskUserID);
                    if (tasker != null)
                    {
                        job.Job.TaskUserName = tasker.DisplayName;
                    }
                }
                ViewData["Model"] = job;
            }
            else
            {
                TempData["FileUploadGID"] = Guid.NewGuid();
            }

            return View();
        }

        /// <summary>
        /// 任务详情
        /// </summary>
        /// <returns></returns>
        public ActionResult TaskDetail(decimal ID, int? UserRole)
        {
            Thread.CurrentThread.CurrentCulture = Culture;
            Thread.CurrentThread.CurrentUICulture = Culture;

            var task = _plan.GetTaskDetail(ID);
            var currentUser = user_x.GetUser_XByName(User.Identity.Name);

            if (task != null)
            {
                var owner = user_x.GetUserByID(task.OwnerID);
                if (owner != null)
                {
                    task.OwnerName = owner.DisplayName;
                }
                var location = user_x.GetSiteBranchBySiteID(task.Location);
                if (location != null)
                {
                    task.LocationName = location.Alias;
                }

                task.JobTypeName = EnumDataSource<EnumUtility.TaskType>.GetDisplayValue((int)task.JobType, "zh-cn");

                ViewData["TaskType"] = (int)task.JobType;
                ViewData["TaskStatus"] = getTaskStatusList(task, UserRole);
                ViewBag.DetailID = ID;

                var fileList = _plan.GetFileList(ID);

                ViewData["Model"] = task;
                TempData["TaskDetail"] = task;
                ViewData["FileList"] = JsonConvert.SerializeObject(fileList);

                var isTaskStatusEnd = task.Status == (int)EnumUtility.TaskStatus.Cancled || task.Status == (int)EnumUtility.TaskStatus.Closed;
                //除责任人和创建人，其他用户没有操作权限，只有查看权限；
                var hasOperateRight = currentUser == null || task.CreateUserID == currentUser.ID || task.OwnerID == currentUser.ID;

                ViewData["TaskIsEnd"] = (UserRole.HasValue && UserRole.Value == (int)EnumUtility.UserRole.View) || isTaskStatusEnd || !hasOperateRight;

                ViewData["CurrentUser"] = currentUser;
            }

            return View();
        }

        /// <summary>
        /// 保存任务
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public JsonResult SaveTask(TaskModel task, List<TaskAttachmentModel> files)
        {
            SetRoles(user_x);
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);

            var result = false;

            if (TempData["TaskDetail"] != null && CurrentUser != null)
            {
                var detail = TempData["TaskDetail"] as TaskModel;

                detail.Status = task.Status;
                detail.UpdateTime = DateTime.Now;
                detail.UpdateUserID = CurrentUser.ID;
                detail.TaskDetail = task.TaskDetail;
                detail.OwnerID = task.OwnerID;

                //已完成则插入完成时间
                if (detail.Status == (int)EnumUtility.TaskStatus.Completed)
                {
                    detail.CompleteTime = DateTime.Now;
                }

                result = _plan.SaveTask(detail, files);
            }

            return Json(result ? "OK" : "Error", JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 是否是任务创建人
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        private bool isCreator(TaskModel task)
        {
            if (task != null)
            {
                var creatorID = task.CreateUserID;
                SetRoles(user_x);
                var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);
                if (CurrentUser != null)
                {
                    return CurrentUser.ID == creatorID;
                }
            }
            return false;
        }

        /// <summary>
        /// 是否是任务责任人
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        private bool isResponsible(TaskModel task)
        {
            if (task != null)
            {
                var ownerID = task.OwnerID;
                SetRoles(user_x);
                var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);
                if (CurrentUser != null)
                {
                    return CurrentUser.ID == ownerID;
                }
            }
            return false;
        }

        /// <summary>
        /// 依据登陆人以及任务状态决定状态列表选项
        /// </summary>
        /// <returns></returns>
        private EnumDataSource<EnumUtility.TaskStatus> getTaskStatusList(TaskModel task, int? UserRole)
        {
            Thread.CurrentThread.CurrentCulture = Culture;
            Thread.CurrentThread.CurrentUICulture = Culture;

            var status = new EnumDataSource<EnumUtility.TaskStatus>();
            var taskStatus = task.Status;

            var iscreator = isCreator(task);
            var isresponsible = isResponsible(task);

            if (UserRole.HasValue && UserRole.Value != 0)
            {  //以不同角色进入
                switch (UserRole)
                {
                    case (int)EnumUtility.UserRole.Creator:
                        if (iscreator)
                        {
                            if (taskStatus == (int)EnumUtility.TaskStatus.InProcess)
                            {
                                //进行中保留全部状态
                            }

                            if (taskStatus == (int)EnumUtility.TaskStatus.Completed)
                            {
                                status.Clear();
                                status.Add(new EnumAdapter<EnumUtility.TaskStatus>((int)EnumUtility.TaskStatus.Completed));
                                status.Add(new EnumAdapter<EnumUtility.TaskStatus>((int)EnumUtility.TaskStatus.Closed));
                                status.Add(new EnumAdapter<EnumUtility.TaskStatus>((int)EnumUtility.TaskStatus.InProcess));
                            }
                        }
                        break;
                    case (int)EnumUtility.UserRole.Responsible:
                        if (isresponsible)
                        {
                            if (taskStatus == (int)EnumUtility.TaskStatus.InProcess)
                            {
                                status.Clear();
                                status.Add(new EnumAdapter<EnumUtility.TaskStatus>((int)EnumUtility.TaskStatus.InProcess));
                                status.Add(new EnumAdapter<EnumUtility.TaskStatus>((int)EnumUtility.TaskStatus.Completed));
                            }
                        }
                        break;
                }

            }
            else
            {
                status.Clear();
            }

            return status;
        }

        #region 巡检对象搜索
        /// <summary>
        /// 业务系统搜索
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public ActionResult SearchBussiness(string Key)
        {
            ViewData["Key"] = Key;

            return View();
        }

        public JsonResult SearchBusinessResult(QueryString query, string ExcludeIDList, int page, int rows, string sort, string order)
        {
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);

            if (!string.IsNullOrWhiteSpace(ExcludeIDList))
            {
                query.ExcludeIDList = JsonConvert.DeserializeObject<List<string>>(ExcludeIDList);
            }

            decimal totalCount = 0;
            var list = _plan.SearchInspectionObject<BusinessSystem>(out totalCount, InspectionObjectType.Business, CurrentUser.Company, query, page, rows, sort, order);

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SearchServer(string Key)
        {
            Thread.CurrentThread.CurrentCulture = Culture;
            Thread.CurrentThread.CurrentUICulture = Culture;

            ViewData["Key"] = Key;
            ViewData["ServerType"] = new EnumDataSource<EnumUtility.ServerType>();
            return View();
        }

        public JsonResult SearchServerResult(QueryString query, string ExcludeIDList, int page, int rows, string sort, string order)
        {
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);

            if (!string.IsNullOrWhiteSpace(ExcludeIDList))
            {
                query.ExcludeIDList = JsonConvert.DeserializeObject<List<string>>(ExcludeIDList);
            }

            decimal totalCount = 0;
            var list = _plan.SearchInspectionObject<ServerObject>(out totalCount, InspectionObjectType.Server, CurrentUser.Company, query, page, rows, sort, order);

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SearchNet(string Key)
        {
            ViewData["Key"] = Key;
            ViewData["Vendor"] = _plan.GetVendorList();
            return View();
        }

        public JsonResult SearchNetResult(QueryString query, string ExcludeIDList, int page, int rows, string sort, string order)
        {
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);

            if (!string.IsNullOrWhiteSpace(ExcludeIDList))
            {
                query.ExcludeIDList = JsonConvert.DeserializeObject<List<string>>(ExcludeIDList);
            }

            decimal totalCount = 0;
            var list = _plan.SearchInspectionObject<NetDevice>(out totalCount, InspectionObjectType.Net, CurrentUser.Company, query, page, rows, sort, order);

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SearchSafety(string Key)
        {
            ViewData["Key"] = Key;
            ViewData["Vendor"] = _plan.GetVendorList();
            return View();
        }

        public JsonResult SearchSafetyResult(QueryString query, string ExcludeIDList, int page, int rows, string sort, string order)
        {
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);

            if (!string.IsNullOrWhiteSpace(ExcludeIDList))
            {
                query.ExcludeIDList = JsonConvert.DeserializeObject<List<string>>(ExcludeIDList);
            }

            decimal totalCount = 0;
            var list = _plan.SearchInspectionObject<SafetyDevice>(out totalCount, InspectionObjectType.Safety, CurrentUser.Company, query, page, rows, sort, order);

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SearchDB(string Key)
        {
            ViewData["Key"] = Key;
            ViewData["Version"] = _plan.GetDBVersionList();
            return View();
        }

        public JsonResult SearchDBResult(QueryString query, string ExcludeIDList, int page, int rows, string sort, string order)
        {
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);

            if (!string.IsNullOrWhiteSpace(ExcludeIDList))
            {
                query.ExcludeIDList = JsonConvert.DeserializeObject<List<string>>(ExcludeIDList);
            }

            decimal totalCount = 0;
            var list = _plan.SearchInspectionObject<DBSystem>(out totalCount, InspectionObjectType.DB, CurrentUser.Company, query, page, rows, sort, order);

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SearchMiddleware(string Key)
        {
            ViewData["Key"] = Key;
            ViewData["Version"] = _plan.GetMiddleVersionList();
            return View();
        }

        public JsonResult SearchMiddlewareResult(QueryString query, string ExcludeIDList, int page, int rows, string sort, string order)
        {
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);

            if (!string.IsNullOrWhiteSpace(ExcludeIDList))
            {
                query.ExcludeIDList = JsonConvert.DeserializeObject<List<string>>(ExcludeIDList);
            }

            decimal totalCount = 0;
            var list = _plan.SearchInspectionObject<MiddleWareSystem>(out totalCount, InspectionObjectType.MiddleWare, CurrentUser.Company, query, page, rows, sort, order);

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SearchStorage(string Key)
        {
            ViewData["Key"] = Key;
            return View();
        }

        public JsonResult SearchStorageResult(QueryString query, string ExcludeIDList, int page, int rows, string sort, string order)
        {
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);

            if (!string.IsNullOrWhiteSpace(ExcludeIDList))
            {
                query.ExcludeIDList = JsonConvert.DeserializeObject<List<string>>(ExcludeIDList);
            }

            decimal totalCount = 0;
            var list = _plan.SearchInspectionObject<StorageSystem>(out totalCount, InspectionObjectType.Storage, CurrentUser.Company, query, page, rows, sort, order);

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SearchBackUp(string Key)
        {
            ViewData["Key"] = Key;
            ViewData["Version"] = _plan.GetDBVersionList();
            return View();
        }

        public JsonResult SearchBackUpResult(QueryString query, string ExcludeIDList, int page, int rows, string sort, string order)
        {
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);

            if (!string.IsNullOrWhiteSpace(ExcludeIDList))
            {
                query.ExcludeIDList = JsonConvert.DeserializeObject<List<string>>(ExcludeIDList);
            }

            decimal totalCount = 0;
            var list = _plan.SearchInspectionObject<DBSystem>(out totalCount, InspectionObjectType.DB, CurrentUser.Company, query, page, rows, sort, order);

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 责任人搜索

        public ActionResult SearchResponsible(bool IsOwner, bool isNotSingle)
        {
            ViewData["AddTitle"] = "选择";

            SetRoles(user_x);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
            {
                throw new Exception("USER_X is null.");
            }
            var sites = user_x.GetSiteBranchByID(USER_X.ID);
            var t = sites.FirstOrDefault(s => s.Name == USER_X.Company);
            if (t != null)
            {
                //省局管理员
                ViewBag.IsGlobalConfigAdmin = IsConfigAdmin && t.Alias.Equals("省局") && !IsOwner;
            }


            //省局管理员获取所有单位
            ViewData["GlobalCompanyName"] = GlobalCompanyName;
            ViewData["CurrentCompany"] = USER_X.Company;
            ViewData["Sites"] = siteBranch.GetSiteALLBranch().Select(o => o.Name).ToList();
            ViewData["isNotSingle"] = isNotSingle;

            return View();
        }

        public ActionResult SearchResponsibleByGroup()
        {
            ViewData["AddTitle"] = "选择";

            SetRoles(user_x);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
            {
                throw new Exception("USER_X is null.");
            }
            var sites = user_x.GetSiteBranchByID(USER_X.ID);
            var t = sites.FirstOrDefault(s => s.Name == USER_X.Company);

            if (t != null)
            {
                var IsGlobalConfig = t.Alias.Equals("省局");
                decimal total = 0;

                ViewData["PlanGroup"] = _plan.GetAllGroup(t.ID, IsGlobalConfig, out total, null, null, "ID", "Ascending");
            }

            return View();
        }

        public JsonResult SerachGroupUserResult(int groupID, int page, int rows, string sort, string order)
        {
            decimal total = 0;
            var users = _plan.GetUsersByGroup(groupID, out total, page, rows, sort, order);
            var userInfos = new List<User_XModel>();

            foreach (var item in users)
            {
                userInfos.Add(user_x.GetUserByID(item.UserID));
            }

            return Json(new { rows = userInfos, total = total }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetDepartment(string company)
        {
            List<string> departmentlist = new List<string>();
            if (!string.IsNullOrEmpty(company))
            {
                if (string.Equals(company, "所有"))
                {
                    departmentlist = DepartmentHelper.GetAllDepartment().Distinct().ToList();
                }
                else
                {
                    departmentlist = DepartmentHelper.GetListDepartment(company).Distinct().ToList();
                }
            }

            return Json(departmentlist, JsonRequestBehavior.AllowGet);
        }

        public JsonResult SerachResult(QueryString query, int page, int rows, string sort, string order)
        {
            decimal totalCount = 0;

            var list = user_x.GetUserListByQueryParameter(out totalCount, query, page, rows, sort, order);

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        #endregion

        public JsonResult MenuList()
        {
            var root = new JsonCollection();

            JsonObject menu1 = new JsonObject();
            menu1.MergeProperty("text", new JsonConstant("待办任务"));
            menu1.MergeProperty("iconCls", new JsonConstant("icon-redo"));
            JsonObject attri = new JsonObject();
            attri.MergeProperty("targetHref", new JsonConstant("/PlanManagement/PendingList"));
            menu1.MergeProperty("attributes", new JsonConstant(attri));
            menu1.MergeProperty("checked", new JsonConstant(true));
            root.AppendObject(menu1);

            //JsonObject menu4 = new JsonObject();
            //menu4.MergeProperty("text", new JsonConstant("已过期任务"));
            //JsonObject attri4 = new JsonObject();
            //attri4.MergeProperty("targetHref", new JsonConstant("/PlanManagement/ClosedList"));
            //menu4.MergeProperty("attributes", new JsonConstant(attri4));
            //root.AppendObject(menu4);

            JsonObject menu2 = new JsonObject();
            menu2.MergeProperty("text", new JsonConstant("待确认任务"));
            menu2.MergeProperty("iconCls", new JsonConstant("icon-redo"));
            JsonObject attri2 = new JsonObject();
            attri2.MergeProperty("targetHref", new JsonConstant("/PlanManagement/CheckInList"));
            menu2.MergeProperty("attributes", new JsonConstant(attri2));
            root.AppendObject(menu2);

            JsonObject menu3 = new JsonObject();
            menu3.MergeProperty("text", new JsonConstant("我创建的计划"));
            menu3.MergeProperty("iconCls", new JsonConstant("icon-redo"));
            JsonObject attri3 = new JsonObject();
            attri3.MergeProperty("targetHref", new JsonConstant("/PlanManagement/MyCreatePlanList"));
            menu3.MergeProperty("attributes", new JsonConstant(attri3));
            root.AppendObject(menu3);

            //只有信息中心主任能看到过期任务提醒
            //信息中心主任
            SetRoles(user_x);
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);
            if (CurrentUser.Position != null && CurrentUser.Position.Equals("信息中心主任", StringComparison.OrdinalIgnoreCase))
            {
                JsonObject menu5 = new JsonObject();
                menu5.MergeProperty("text", new JsonConstant("过期任务提醒"));
                menu5.MergeProperty("iconCls", new JsonConstant("icon-redo"));
                JsonObject attri5 = new JsonObject();
                attri5.MergeProperty("targetHref", new JsonConstant("/PlanManagement/OverFlagTip"));
                menu5.MergeProperty("attributes", new JsonConstant(attri5));
                root.AppendObject(menu5);
            }

            JsonObject menu6 = new JsonObject();
            menu6.MergeProperty("text", new JsonConstant("任务搜索"));
            menu6.MergeProperty("iconCls", new JsonConstant("icon-redo"));
            JsonObject attri6 = new JsonObject();
            attri6.MergeProperty("targetHref", new JsonConstant("/PlanManagement/Search"));
            menu6.MergeProperty("attributes", new JsonConstant(attri6));
            root.AppendObject(menu6);

            JsonObject menu7 = new JsonObject();
            menu7.MergeProperty("text", new JsonConstant("计划搜索"));
            menu7.MergeProperty("iconCls", new JsonConstant("icon-redo"));
            JsonObject attri7 = new JsonObject();
            attri7.MergeProperty("targetHref", new JsonConstant("/PlanManagement/PlanSearch"));
            menu7.MergeProperty("attributes", new JsonConstant(attri7));
            root.AppendObject(menu7);

            return new NRemedy.MVC.UI.RawJsonResult()
            {
                Data = root.ToString(),
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        [HttpPost]
        public JsonResult GetCalendarPending(int? Year, int? month)
        {
            SetRoles(user_x);
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);
            var result = new Dictionary<string, List<TaskModel>>();
            if (CurrentUser != null)
            {
                if (!Year.HasValue) { Year = DateTime.Now.Year; }
                if (!month.HasValue) { month = DateTime.Now.Month; }

                result = _plan.GetPendingTaskByYearAndMonth(CurrentUser.ID, Year.Value, month.Value);

            }
            return Json(result, JsonRequestBehavior.AllowGet);

        }

        public ContentResult PendingList()
        {
            var html = this.GetHtmlHelper("PendingList").RenderPlanPendingList();
            return Content(html);
        }

        /// <summary>
        /// 获取待办任务
        /// </summary>
        /// <param name="page">当前页[1,2...]</param>
        /// <param name="rows">每页条数</param>
        /// <param name="sort">排序字段名</param>
        /// <param name="order">排序方式[asc,desc]</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetPendingList(int page, int rows, string sort, string order)
        {
            decimal totalCount = 0;

            SetRoles(user_x);
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);

            if (string.IsNullOrEmpty(sort)) { sort = "JobNo"; }
            if (string.Equals(sort, "CreateUserName")) { sort = "CreateUserID"; }
            if (string.IsNullOrEmpty(order)) { order = "Ascending"; }
            var list = _plan.GetTaskByUserID(CurrentUser.ID, page, rows, out totalCount, false, sort, order);

            foreach (var item in list)
            {
                var creator = user_x.GetUserByID(item.CreateUserID);
                if (creator != null)
                {
                    item.CreateUserName = creator.DisplayName;
                }
            }

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        public ContentResult CheckInList()
        {
            var html = this.GetHtmlHelper("CheckInList").RenderCheckInList();
            return Content(html);
        }

        [HttpPost]
        public JsonResult GetCheckInList(int page, int rows, string sort, string order)
        {
            decimal totalCount = 0;

            SetRoles(user_x);
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);

            if (string.IsNullOrEmpty(sort)) { sort = "JobNo"; }
            if (string.Equals(sort, "CreateUserName")) { sort = "CreateUserID"; }
            if (string.IsNullOrEmpty(order)) { order = "Ascending"; }
            var list = _plan.GetTaskByCreateUserID(CurrentUser.ID, page, rows, out totalCount, sort, order);

            foreach (var item in list)
            {
                var creator = user_x.GetUserByID(item.CreateUserID);
                if (creator != null)
                {
                    item.CreateUserName = creator.DisplayName;
                }
            }

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        public ContentResult MyCreatePlanList()
        {
            var html = this.GetHtmlHelper("MyCreatePlanList").RenderMyCreatePlanList();
            return Content(html);
        }

        [HttpPost]
        public JsonResult GetMyCreatePlanList(int page, int rows, string sort, string order)
        {
            decimal totalCount = 0;

            SetRoles(user_x);
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);

            if (string.IsNullOrEmpty(sort)) { sort = "ID"; }
            if (string.Equals(sort, "JobOwnerName")) { sort = "JobOwnerID"; }
            if (string.IsNullOrEmpty(order)) { order = "Ascending"; }
            var list = _plan.GetPlanByUserID(CurrentUser.ID, page, rows, out totalCount, sort, order);

            list.ForEach(x => x.JobOwnerName = user_x.GetUserByID(x.JobOwnerID).DisplayName);

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult GetRelatedTaskList(int planID, int page, int rows, string sort, string order)
        {
            decimal totalCount = 0;

            if (string.IsNullOrEmpty(sort)) { sort = "BeginDate"; }
            if (string.Equals(sort, "OwnerName")) { sort = "OwnerID"; }
            if (string.IsNullOrEmpty(order)) { order = "Descending"; }
            var list = _plan.GetTaskByJobID(planID, page, rows, out totalCount, sort, order);

            foreach (var item in list)
            {
                var owner = user_x.GetUserByID(item.OwnerID);
                if (owner != null)
                {
                    item.OwnerName = owner.DisplayName;
                }
            }

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        public ContentResult ClosedList()
        {
            var html = this.GetHtmlHelper("ClosedList").RenderClosedList();
            return Content(html);
        }

        [HttpPost]
        public JsonResult GetClosedList(int page, int rows, string sort, string order)
        {
            decimal totalCount = 0;

            SetRoles(user_x);
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);

            if (string.IsNullOrEmpty(sort)) { sort = "JobNo"; }
            if (string.Equals(sort, "CreateUserName")) { sort = "CreateUserID"; }
            if (string.IsNullOrEmpty(order)) { order = "Ascending"; }
            var list = _plan.GetTaskByUserID(CurrentUser.ID, page, rows, out totalCount, true, sort, order);

            foreach (var item in list)
            {
                var creator = user_x.GetUserByID(item.CreateUserID);
                if (creator != null)
                {
                    item.CreateUserName = creator.DisplayName;
                }
            }

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetThirdPartyInspection(int page, int rows, string sort, string order)
        {
            decimal totalCount = 0;

            if (string.IsNullOrEmpty(sort)) { sort = "ID"; }
            if (string.Equals(sort, "CreatorName")) { sort = "CreatorID"; }
            if (string.IsNullOrEmpty(order)) { order = "Descending"; }
            var list = _plan.GetAllInspectionType(out totalCount, page, rows, sort, order);

            foreach (var item in list)
            {
                var creator = user_x.GetUserByID(item.CreatorID);
                if (creator != null)
                {
                    item.CreatorName = creator.DisplayName;
                }
            }

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 计划任务搜索页面
        /// </summary>
        /// <returns></returns>
        public ContentResult Search()
        {
            Thread.CurrentThread.CurrentCulture = Culture;
            Thread.CurrentThread.CurrentUICulture = Culture;

            ViewDataDictionary viewdata = new ViewDataDictionary();

            viewdata["IsGlobalConfigAdmin"] = false;
            SetRoles(user_x);
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);
            var sites = user_x.GetSiteBranchByID(CurrentUser.ID);
            var t = sites.FirstOrDefault(s => s.Name == CurrentUser.Company);
            if (t != null)
            {
                //省局管理员
                viewdata["IsGlobalConfigAdmin"] = IsConfigAdmin && t.Alias.Equals("省局");
            }
            viewdata["Location"] = t;

            var status = new EnumDataSource<EnumUtility.TaskStatus>();
            var taskType = new EnumDataSource<EnumUtility.TaskType>();
            var taskRange = _plan.GetSiteALLBranch().OrderBy(x => x.LocationID).ToList();

            viewdata["TaskStatus"] = status;
            viewdata["TaskType"] = taskType;
            viewdata["TaskRange"] = taskRange;

            var html = this.GetHtmlHelper("Search").RenderSearchPage(viewdata);
            return Content(html);
        }

        public ContentResult PlanSearch()
        {
            Thread.CurrentThread.CurrentCulture = Culture;
            Thread.CurrentThread.CurrentUICulture = Culture;

            ViewDataDictionary viewdata = new ViewDataDictionary();
            viewdata["PlanStatus"] = new EnumDataSource<EnumUtility.PlanStatus>();
            var taskType = new EnumDataSource<EnumUtility.TaskType>();

            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);
            var location = user_x.GetSiteBranchByID(CurrentUser.ID).FirstOrDefault(s => s.Name == CurrentUser.Company);
            if (location != null)
            {
                if (!location.Alias.Equals("省局"))
                {
                    taskType.RemoveAll(x => x.EnumValue == (int)EnumUtility.TaskType.General);
                }
            }

            viewdata["TaskType"] = taskType;
            var html = this.GetHtmlHelper("Search").RenderPlanSearchPage(viewdata);
            return Content(html);
        }

        /// <summary>
        /// 第三方巡检维护
        /// </summary>
        /// <returns></returns>
        public ActionResult ConfigInspection()
        {
            base.SetRoles(user_x);
            ViewBag.IsConfigAdmin = IsConfigAdmin;

            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            return View();
        }

        /// <summary>
        /// 计划接口人维护
        /// </summary>
        /// <returns></returns>
        public ActionResult ConfigInterfacePeople()
        {
            base.SetRoles(user_x);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            return View();
        }

        /// <summary>
        /// 任务组维护
        /// </summary>
        /// <returns></returns>
        public ActionResult ConfigGroup()
        {
            base.SetRoles(user_x);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            return View();
        }

        public ContentResult OverFlagTip()
        {
            var html = this.GetHtmlHelper("OverFlagTip").RenderOverFlagTip();
            return Content(html);
        }

        public JsonResult GetOverflagList(int page, int rows, string sort, string order)
        {
            decimal totalCount = 0;
            SetRoles(user_x);
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);
            var location = user_x.GetSiteIDByName(CurrentUser.Name).FirstOrDefault();
            var list = new List<TaskModel>();

            if (location != null)
            {
                if (string.IsNullOrEmpty(sort)) { sort = "JobNo"; }
                if (string.Equals(sort, "CreateUserName")) { sort = "CreateUserID"; }
                if (string.IsNullOrEmpty(order)) { order = "Ascending"; }
                list = _plan.GetTaskByLocation(location.SiteID, page, rows, out totalCount, true, sort, order);

                foreach (var item in list)
                {
                    var creator = user_x.GetUserByID(item.CreateUserID);
                    if (creator != null)
                    {
                        item.CreateUserName = creator.DisplayName;
                    }
                }
            }

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetFileList()
        {
            var task = TempData["TaskDetail"] as TaskModel;
            TempData["TaskDetail"] = task;

            var list = _plan.GetFileList(task.ID);

            foreach (var item in list)
            {
                var uploader = user_x.GetUserByID(item.UpLoadUserID);
                if (uploader != null)
                {
                    item.UpLoadUserName = uploader.DisplayName;
                }
            }

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetFileListUsingJobID()
        {
            var task = TempData["TaskDetail"] as TaskModel;
            TempData["TaskDetail"] = task;

            var list = _plan.GetFileList(task.JobId);

            foreach (var item in list)
            {
                var uploader = user_x.GetUserByID(item.UpLoadUserID);
                if (uploader != null)
                {
                    item.UpLoadUserName = uploader.DisplayName;
                }
            }

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetJobFileList()
        {
            var list = new List<TaskAttachmentModel>();
            if (TempData["JobDetail"] != null)
            {  //计划详情
                var job = TempData["JobDetail"] as ScheduleJob;
                TempData["JobDetail"] = job;

                list = _plan.GetFileList(job.Job.ID);
            }
            else if (TempData["FileUploadGID"] != null)
            { //新建计划
                var GID = (Guid)TempData["FileUploadGID"];
                TempData["FileUploadGID"] = GID;

                list = _plan.GetFileListByGID(GID.ToString());
            }


            foreach (var item in list)
            {
                var uploader = user_x.GetUserByID(item.UpLoadUserID);
                if (uploader != null)
                {
                    item.UpLoadUserName = uploader.DisplayName;
                }
            }

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public ActionResult FileUpload()
        {
            var task = TempData["TaskDetail"] as TaskModel;
            TempData["TaskDetail"] = task;

            return View();
        }

        [HttpPost]
        public ActionResult FileUpload(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                try
                {
                    SetRoles(user_x);
                    var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);

                    var task = TempData["TaskDetail"] as TaskModel;
                    TempData["TaskDetail"] = task;

                    // extract only the fielname
                    var fileName = Path.GetFileName(file.FileName);
                    // store the file inside ~/PlanUploadFilePath folder
                    var today = DateTime.Today.ToString("yyyyMMdd");
                    var guid = Guid.NewGuid().ToString();

                    string filePath = Server.MapPath(Path.Combine(ConfigurationManager.AppSettings["PlanUploadFilePath"], today, guid));

                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }

                    string fullFilePath = Path.Combine(filePath, fileName);
                    if (System.IO.File.Exists(fullFilePath))
                    {
                        return Content("文件已经存在");
                    }

                    file.SaveAs(fullFilePath);

                    var fileModel = new TaskAttachmentModel()
                    {
                        FileName = fileName,
                        RelationID = task.ID,
                        UpLoadPath = Path.Combine(ConfigurationManager.AppSettings["PlanUploadFilePath"], today, guid, fileName).Replace('\\', '/'),
                        UploadTime = DateTime.Now,
                        UpLoadUserID = CurrentUser.ID
                    };

                    _plan.AddFile(fileModel);
                }
                catch (Exception e)
                {
                    return Content("上传失败，请重新上传！");
                }
            }
            return RedirectToAction("FileUpload");
        }


        public ActionResult FileUpload_Job()
        {
            return View();
        }

        [HttpPost]
        public ActionResult FileUpload_Job(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                try
                {
                    SetRoles(user_x);
                    var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);

                    decimal relationID = 0;
                    Guid GID = new Guid();
                    if (TempData["JobDetail"] != null)
                    {  //计划详情
                        var job = TempData["JobDetail"] as ScheduleJob;
                        TempData["JobDetail"] = job;

                        relationID = job.Job.ID;
                    }

                    if (TempData["FileUploadGID"] != null)
                    { //新建计划
                        GID = (Guid)TempData["FileUploadGID"];
                        TempData["FileUploadGID"] = GID;
                    }

                    // extract only the fielname
                    var fileName = Path.GetFileName(file.FileName);
                    // store the file inside ~/PlanUploadFilePath folder
                    var today = DateTime.Today.ToString("yyyyMMdd");
                    var guid = Guid.NewGuid().ToString();

                    string filePath = Server.MapPath(Path.Combine(ConfigurationManager.AppSettings["PlanUploadFilePath"], today, guid));

                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }

                    string fullFilePath = Path.Combine(filePath, fileName);
                    if (System.IO.File.Exists(fullFilePath))
                    {
                        return Content("文件已经存在");
                    }

                    file.SaveAs(fullFilePath);

                    var fileModel = new TaskAttachmentModel()
                    {
                        FileName = fileName,
                        RelationID = relationID,
                        UpLoadPath = Path.Combine(ConfigurationManager.AppSettings["PlanUploadFilePath"], today, guid, fileName).Replace('\\', '/'),
                        UploadTime = DateTime.Now,
                        UpLoadUserID = CurrentUser.ID,
                        GID = GID.ToString()
                    };

                    _plan.AddFile(fileModel);
                }
                catch (Exception e)
                {
                    return Content("上传失败，请重新上传！");
                }
            }

            return RedirectToAction("FileUpload_Job");
        }

        [HttpPost]
        public JsonResult FileDelete(int ID)
        {
            var file = _plan.GetFileByID(ID);
            if (file != null)
            {
                //本地删除
                string filePath = Server.MapPath(ConfigurationManager.AppSettings["UploadFilePath"]);
                string fullFilePath = Path.Combine(filePath, file.FileName);
                if (System.IO.File.Exists(fullFilePath))
                {
                    System.IO.File.Delete(fullFilePath);
                }
                //数据库删除
                var result = _plan.DeleteFile(ID) ? "OK" : "Error";

                return Json(result, JsonRequestBehavior.AllowGet);
            }

            return Json("Error", JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult PostSearchTask(SearchParam param, int page, int rows, string sort, string order)
        {
            decimal totalCount = 0;

            if (string.IsNullOrEmpty(sort)) { sort = "JobNo"; }
            if (string.Equals(sort, "OwnerName")) { sort = "OwnerID"; }
            if (string.IsNullOrEmpty(order)) { order = "Ascending"; }
            var list = _plan.SearchTask(param, out totalCount, page, rows, sort, order);

            if (list != null)
            {
                foreach (var item in list)
                {
                    var Owner = user_x.GetUserByID(item.OwnerID);
                    if (Owner != null)
                    {
                        item.OwnerName = Owner.DisplayName;
                    }
                }
            }

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult PostSearchPlan(SearchParam param, int page, int rows, string sort, string order)
        {
            SetRoles(user_x);
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);
            var sites = user_x.GetSiteBranchByID(CurrentUser.ID);
            var t = sites.FirstOrDefault(s => s.Name == CurrentUser.Company);

            if (t != null)
            {
                param.CreatorLocation = (int)t.ID;
            }

            decimal totalCount = 0;

            if (string.IsNullOrEmpty(sort)) { sort = "ID"; }
            if (string.Equals(sort, "JobOwnerName")) { sort = "JobOwnerID"; }
            if (string.IsNullOrEmpty(order)) { order = "Ascending"; }
            var list = _plan.SearchJob(param, out totalCount, page, rows, sort, order);

            foreach (var item in list)
            {
                var creator = user_x.GetUserByID(item.JobOwnerID);
                if (creator != null)
                {
                    item.JobOwnerName = creator.DisplayName;
                }
            }

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        #region 第三方巡检类型操作
        [HttpPost]
        public JsonResult CreateInsType(InspectionType type)
        {
            SetRoles(user_x);
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);

            type.CreateTime = DateTime.Now;
            type.Invalid = 1;
            type.CreatorID = CurrentUser.ID;
            type.CreatorName = CurrentUser.DisplayName;

            var result = _plan.SaveInspectionType(type);

            return Json(result ? "OK" : "Error", JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult DeleteInsType(decimal ID)
        {
            var result = _plan.DeleteInspectionType(ID) ? "OK" : "Error";

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region 计划操作

        /// <summary>
        /// 计划创建或者更新(包含计划对应的周期对象)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Create(JobModel job, List<CycleModel> cycle, AnnouncementModel bulletin)
        {
            var result = true;

            if (job != null)
            {
                if (TempData["FileUploadGID"] != null)
                {
                    var GID = (Guid)TempData["FileUploadGID"];
                    TempData["FileUploadGID"] = GID;
                    job.FileGID = GID.ToString();
                }

                if (_plan.IsJobNameExisted(job.JobName, job.ID != 0 ? job.ID : default(Nullable<decimal>)))
                {
                    return Json("计划名已存在", JsonRequestBehavior.AllowGet);
                }

                if (job.JobType == (int)EnumUtility.TaskType.Daily)
                {
                    //日常巡检的任务范围是责任人所在的地市
                    var user = user_x.GetUserByID(job.TaskUserID);
                    var owner = user_x.GetSiteBranchByID(job.TaskUserID).FirstOrDefault(x => x.Name == user.Company);

                    if (owner != null)
                    {
                        job.JobRange = string.Format("{0};", owner.ID);
                    }
                }

                if (job.ID == 0)
                {
                    job.CreateTime = DateTime.Now;
                    job.UpdateTime = DateTime.Now;

                    if (bulletin != null)
                    {
                        bulletin.CreateTime = DateTime.Now;
                        bulletin.CreateBy = job.JobOwnerID;
                        bulletin.InValid = 1;
                    }

                    cycle.ForEach(x => x.CreateDateTime = DateTime.Now);

                    result = _plan.SaveJob(new ScheduleJob() { Job = job, Cycle = cycle, Bulletin = bulletin });
                }
                else
                {
                    result = _plan.UpdateJob(job);
                }
            }

            return Json(result ? "OK" : "Error", JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 电子公告
        /// <summary>
        /// 电子公告
        /// </summary>
        /// <returns></returns>
        public ActionResult Announcement()
        {
            base.SetRoles(user_x);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            return View();
        }


        /// <summary>
        /// 电子公告列表
        /// </summary>
        /// <returns></returns>
        public ActionResult AnnouncementList()
        {
            base.SetRoles(user_x);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            return View();
        }

        /// <summary>
        /// 电子公告详情页
        /// </summary>
        /// <returns></returns>
        public ActionResult AnnouncementDetail(int ID, bool canEdit)
        {
            var detail = _plan.GetAnnouncementDetail(ID);

            ViewData["canEdit"] = canEdit;
            return View(detail);
        }

        [HttpPost]
        public JsonResult GetAnnouncementList(int page, int rows, string sort, string order)
        {
            decimal totalCount = 0;

            if (string.IsNullOrEmpty(sort)) { sort = "BeginTime"; }
            if (string.Equals(sort, "CreateByName")) { sort = "CreateBy"; }
            if (string.IsNullOrEmpty(order)) { order = "Descending"; }

            var list = _plan.GetAllAnnouncement(out totalCount, page, rows, false, sort, order);

            foreach (var item in list)
            {
                var user = user_x.GetUserByID(item.CreateBy);
                if (user != null)
                {
                    item.CreateByName = user.DisplayName;
                }
            }

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult GetAnnouncementListNoOver(int page, int rows, string sort, string order)
        {
            decimal totalCount = 0;

            if (string.IsNullOrEmpty(sort)) { sort = "BeginTime"; }
            if (string.Equals(sort, "CreateByName")) { sort = "CreateBy"; }
            if (string.IsNullOrEmpty(order)) { order = "Descending"; }

            var list = _plan.GetAllAnnouncement(out totalCount, page, rows, true, sort, order);

            foreach (var item in list)
            {
                var user = user_x.GetUserByID(item.CreateBy);
                if (user != null)
                {
                    item.CreateByName = user.DisplayName;
                }
            }

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult DeleteAnnouncement(decimal ID)
        {
            var result = _plan.DeleteAnnouncement(ID) ? "OK" : "Error";

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult AddAnnouncement(AnnouncementModel data)
        {
            var result = false;

            if (data != null)
            {
                if (data.ID == 0)
                {
                    SetRoles(user_x);
                    var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);
                    data.InValid = 1;
                    data.CreateBy = CurrentUser.ID;
                    data.CreateTime = DateTime.Now;

                    result = _plan.CreateAnnouncement(data);
                }
                else
                {
                    result = _plan.UpdateAnnouncement(data);
                }
            }


            return Json(result ? "OK" : "Error", JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region 计划接口人
        /// <summary>
        /// 获取地市对应的计划接口人
        /// </summary>
        /// <returns></returns>
        public JsonResult GetPlanLocationOwner()
        {
            SetRoles(user_x);
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);
            var sites = user_x.GetSiteBranchByID(CurrentUser.ID);
            var t = sites.FirstOrDefault(s => s.Name == CurrentUser.Company);

            var people = new PlanLocationOwner();

            if (t != null)
            {
                people = _plan.GetInterfacePeopleByLocationID(t.ID);
                people.LocationName = t.Name;

                if (people != null)
                {
                    var owner = user_x.GetUserByID(people.OwnerID);
                    if (owner != null)
                    {
                        people.OwnerName = owner.DisplayName;
                    }
                }
            }

            return Json(new List<PlanLocationOwner>() { people }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 保存计划接口人
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SavePlanLocationOwner(decimal ownerID)
        {
            var CurrentUser = user_x.GetUser_XByName(User.Identity.Name);
            var sites = user_x.GetSiteBranchByID(CurrentUser.ID);
            var t = sites.FirstOrDefault(s => s.Name == CurrentUser.Company);

            var row = false;

            if (t != null)
            {
                row = _plan.SaveInterfacePeople(ownerID, t.ID);
            }

            return Json(row ? "OK" : "Error", JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 计划任务组

        public JsonResult GetAllGroup(int page, int rows, string sort, string order)
        {
            SetRoles(user_x);
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
            {
                throw new Exception("USER_X is null.");
            }
            var sites = user_x.GetSiteBranchByID(USER_X.ID);
            var t = sites.FirstOrDefault(s => s.Name == USER_X.Company);

            //省局管理员
            var isGlobalAdmin = IsConfigAdmin && t.Alias.Equals("省局");

            decimal totalCount = 0;

            if (string.IsNullOrEmpty(sort)) { sort = "ID"; }
            if (string.Equals(sort, "CreatorName")) { sort = "CreatorID"; }
            if (string.IsNullOrEmpty(order)) { order = "Descending"; }

            var groups = _plan.GetAllGroup(t.ID, isGlobalAdmin, out totalCount, page, rows, sort, order);

            foreach (var item in groups)
            {
                var creator = user_x.GetUserByID(item.CreatorID);
                if (creator != null)
                {
                    item.CreatorName = creator.DisplayName;
                }
            }

            return Json(new { rows = groups, total = totalCount }, JsonRequestBehavior.AllowGet);

        }

        /// <summary>
        /// 新建计划任务组
        /// </summary>
        /// <param name="groupName"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveGroup(string groupName)
        {
            SetRoles(user_x);
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
            {
                throw new Exception("USER_X is null.");
            }
            var sites = user_x.GetSiteBranchByID(USER_X.ID);
            var t = sites.FirstOrDefault(s => s.Name == USER_X.Company);

            if (t != null)
            {
                var model = new PlanGroupModel()
                {
                    GroupName = groupName.Trim(),
                    GroupType = (int)EnumUtility.PlanGroupType.Custom,
                    CreatorID = USER_X.ID,
                    Invalid = 1,
                    LocationID = t.ID,
                    CreateTime = DateTime.Now
                };

                var result = _plan.SavePlanGroup(model);

                return Json(result ? "OK" : "Error", JsonRequestBehavior.AllowGet);
            }

            return Json("Error", JsonRequestBehavior.AllowGet);

        }

        public JsonResult DeleteGroup(decimal ID)
        {
            var model = _plan.GetGroupByID(ID);

            if (model != null)
            {
                model.Invalid = 0;
                var result = _plan.UpdatePlanGroup(model);

                return Json(result ? "OK" : "Error", JsonRequestBehavior.AllowGet);
            }

            return Json("Error", JsonRequestBehavior.AllowGet);
        }

        public JsonResult UpdateGroupName(string groupName)
        {
            var group = TempData["Group"] as PlanGroupModel;
            TempData["Group"] = group;

            if (group != null)
            {
                group.GroupName = groupName;
                var result = _plan.UpdatePlanGroup(group);

                return Json(result ? "OK" : "Error", JsonRequestBehavior.AllowGet);
            }

            return Json("Error", JsonRequestBehavior.AllowGet);
        }

        public ActionResult GroupUserList(decimal GroupID)
        {
            var group = _plan.GetGroupByID(GroupID);
            ViewData["Group"] = group;
            TempData["Group"] = group;

            return View();
        }

        public JsonResult GetGroupUser(int page, int rows, string sort, string order)
        {
            var group = TempData["Group"] as PlanGroupModel;
            TempData["Group"] = group;

            decimal totalCount = 0;

            if (string.IsNullOrEmpty(sort)) { sort = "USERID"; }
            if (string.Equals(sort, "UserName")) { sort = "UserID"; }
            if (string.IsNullOrEmpty(order)) { order = "Ascending"; }
            var user = _plan.GetUsersByGroup(group.ID, out totalCount, page, rows, sort, order);

            foreach (var item in user)
            {
                var userInfo = user_x.GetUserByID(item.UserID);
                if (userInfo != null)
                {
                    item.UserName = userInfo.DisplayName;
                    item.Company = userInfo.Company;
                    item.Department = userInfo.Department;
                    item.Position = userInfo.Position;
                }
            }

            return Json(new { rows = user, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult AddGroupUsers(List<decimal> users)
        {
            var group = TempData["Group"] as PlanGroupModel;
            TempData["Group"] = group;

            var result = _plan.AddUserListIntoGroup(group.ID, users);

            return Json(result ? "OK" : "Error", JsonRequestBehavior.AllowGet);
        }

        public JsonResult DeleteGroupUser(int userID)
        {
            var group = TempData["Group"] as PlanGroupModel;
            TempData["Group"] = group;

            var result = _plan.DeleteUserFromGroup(group.ID, userID);

            return Json(result ? "OK" : "Error", JsonRequestBehavior.AllowGet);
        }


        #endregion

        public ActionResult ExportInspectionToExcel()
        {
            return View();
        }

        /// <summary>
        /// 将巡检内容导出excel
        /// </summary>
        /// <param name="detail">巡检内容的json格式数据</param>
        [HttpPost]
        public void ExportInspectionToExcel(string dataDetail)
        {
            if (!string.IsNullOrEmpty(dataDetail))
            {
                var detail = JsonConvert.DeserializeObject<InspectionResult>(dataDetail);
                if (detail != null)
                {
                    HSSFWorkbook book = new HSSFWorkbook();
                    PropertyInfo[] properties = detail.GetType().GetProperties();
                    foreach (var prop in properties)
                    {
                        if (typeof(IList).IsAssignableFrom(prop.PropertyType) && prop.PropertyType.IsGenericType)
                        {
                            var inspValue = (IList)(prop.GetValue(detail, null));

                            if (inspValue != null && inspValue.Count > 0)
                            {
                                var attr = Attribute.GetCustomAttribute(prop, typeof(InspectionTitleAttribute));
                                if (attr != null)
                                {
                                    //create sheet
                                    var sheetName = ((InspectionTitleAttribute)attr).Title;
                                    var sheet = book.CreateSheet(sheetName);
                                    ExportHelper.WriteSheetTitle(book, sheet, inspValue);
                                    ExportHelper.WriteSheetData(book, sheet, inspValue, sheetName.Trim().Equals("服务器", StringComparison.OrdinalIgnoreCase) ? 2 : 1);
                                }
                            }
                        }
                    }

                    var fileFullPath = Path.Combine(CreateUploadFilePath(), "日常巡检导出结果.xls");
                    using (FileStream stream = System.IO.File.OpenWrite(fileFullPath))
                    {
                        book.Write(stream);
                    }
                    //写入临时文件
                    ExportFileToResponse(fileFullPath);

                    Response.Close();
                }
            }
        }
    }


}
